[AWS CDK] Stack内の全てのリソースに対してRemovalPolicyを設定してみた
リソースごとにRemovalPolicyやDeletionPolicyを設定するのが面倒
こんにちは、のんピ(@non____97)です。
皆さんはAWS CDKやCloudFormationを使用していて、リソースごとにRemovalPolicyやDeletionPolicyを設定するのが面倒だなと思ったことはありますか? 私はあります。
Stack内のリソースを完全に削除したい際、KMSキーやAWS Backup VaultなどデフォルトのDeletionPolicyがRETAIN
のものが含まれていると、都度リソースごとにDELETE
を設定してあげる必要があります。
また、以下記事で紹介しているようにStackをリファクタリングする場合は、一度DeletionPolicyをRETAIN
に変更して、インポートをしてあげる必要があります。
その他にも、万が一Stackの削除保護が解除されてしまい、そのままStackが削除されてしまうことを防ぐためにもDeletionPolicyをRETAIN
にする場面もあるでしょう。
大量のリソースがある場合、リソース個別にRemovalPolicyやDeletionPolicyを設定するのは大変です。
ということで、今回はAWS CDKを用いてStack内の全てのリソースに対してRemovalPolicyを設定してみました。
AWS CDKのコードの紹介
やり方は非常にシンプルです。
applyRemovalPolicyToAll()
というConstructに対してRemovalPolicyを設定する関数を用意し、子Construct分だけ再起的に呼び出します。
今回は以下記事で使用したコードに追加してみます。
実際のコードは以下のとおりです。
import * as cdk from "aws-cdk-lib";
import { Construct, IConstruct } from "constructs";
import { FsxnResourcesProperty } from "../parameter";
import { PlConstruct } from "./construct/pl-construct";
import { KmsConstruct } from "./construct/kms-construct";
import { SecurityGroupConstruct } from "./construct/securitygroup-construct";
import { BackupConstruct } from "./construct/backup-construct";
import { FsxnVolumeConstruct } from "./construct/fsxn-volume-construct";
import { MonitoringConstruct } from "./construct/monitoring-construct";
export interface FsxnResourcesStackProps
extends cdk.StackProps,
FsxnResourcesProperty {}
export class FsxnResourcesStack extends cdk.Stack {
constructor(scope: Construct, id: string, props: FsxnResourcesStackProps) {
super(scope, id, props);
// Prefix List
if (props.prefixListsProperty) {
new PlConstruct(this, "PlConstruct", {
systemProperty: props.systemProperty,
prefixListsProperty: props.prefixListsProperty,
});
}
// KMS Key
if (props.kmsKeyProperty) {
new KmsConstruct(this, "KmsConstruct", {
systemProperty: props.systemProperty,
kmsKeyProperty: props.kmsKeyProperty,
});
}
// Security Group
if (props.securityGroupProperty) {
new SecurityGroupConstruct(this, "SecurityGroupConstruct", {
systemProperty: props.systemProperty,
securityGroupProperty: props.securityGroupProperty,
});
}
// AWS Backup
const backupConstruct = props.backupProperty
? new BackupConstruct(this, "BackupConstruct", {
systemProperty: props.systemProperty,
backupProperty: props.backupProperty,
})
: undefined;
// FSxN Volume
const fsxnVolumeConstruct =
props.fsxnVolumesProperty && props.fsxnFileSystemProperty
? new FsxnVolumeConstruct(this, "FsxnVolumeConstruct", {
systemProperty: props.systemProperty,
fsxnFileSystemProperty: props.fsxnFileSystemProperty,
fsxnVolumesProperty: props.fsxnVolumesProperty,
backupSelectionName: backupConstruct?.backupSelectionName,
})
: undefined;
props.monitoringProperty && props.fsxnFileSystemProperty
? new MonitoringConstruct(this, "MonitoringConstruct", {
systemProperty: props.systemProperty,
fsxnFileSystemProperty: props.fsxnFileSystemProperty,
monitoringProperty: props.monitoringProperty,
fsvols: fsxnVolumeConstruct?.fsvols,
backupVault: backupConstruct?.backupVault,
})
: undefined;
// Set Removal Policy
if (!props.removalPolicyProperty) {
return;
}
this.applyRemovalPolicyToAll(this, props.removalPolicyProperty);
}
private applyRemovalPolicyToAll(
construct: IConstruct,
removalPolicy: cdk.RemovalPolicy
): void {
if (construct instanceof cdk.CfnResource) {
construct.applyRemovalPolicy(removalPolicy);
}
construct.node.children.forEach((child) => {
this.applyRemovalPolicyToAll(child, removalPolicy);
});
}
}
今回はStack内の全リソースのRemovalPolicyを変更したかったので、このようにしています。
同様の仕組みで特定Constructツリーは以下のリソースのみRemovalPolicyを変更するということも可能です。
また、再起処理のループの中でchild
に対してinstanceof cdk.aws_rds.CfnDBInstance
などとリソース判定をしてあげれば、特定リソースに対してのみRemovalPolicyを設定してあげるということも可能です。
やってみた
RemovalPolicy.RETAIN_ON_UPDATE_OR_DELETE を設定
実際にやってみます。
全てのリソースにRemovalPolicy.RETAIN_ON_UPDATE_OR_DELETE
を設定します。
RemovalPolicy.RETAIN_ON_UPDATE_OR_DELETE
が設定されたリソースは、DeletionPolicyはRetainExceptOnCreate
、UpdateReplacePolicy
はRetain
が設定されます。
RetainExceptOnCreate
の詳細は以下記事をご覧ください。
RemovalPolicyの指定は以下のように行います。
import * as cdk from "aws-cdk-lib";
import { FsxnResourcesStackProperty } from "../types";
import { systemConfig } from "./system-config";
import { kmsKeyConfig } from "./kms-config";
import { securityGroupConfig } from "./securitygroup-config";
import { prefixListsConfig } from "./pl-config";
import { fsxnFileSystemConfig } from "./fsxn-filesystem-config";
import { backupConfig } from "./backup-config";
import { fsxnVolumesConfig } from "./fsxn-volume-config";
import { monitoringConfig } from "./monitoring-config";
import { tagsConfig } from "./tags-config";
export const fsxnResourcesStackProperty: FsxnResourcesStackProperty = {
env: {
account: process.env.CDK_DEFAULT_ACCOUNT,
region: process.env.CDK_DEFAULT_REGION,
},
props: {
systemProperty: systemConfig,
kmsKeyProperty: kmsKeyConfig,
prefixListsProperty: prefixListsConfig,
securityGroupProperty: securityGroupConfig,
fsxnFileSystemProperty: fsxnFileSystemConfig,
backupProperty: backupConfig,
fsxnVolumesProperty: fsxnVolumesConfig,
monitoringProperty: monitoringConfig,
removalPolicyProperty: cdk.RemovalPolicy.RETAIN_ON_UPDATE_OR_DELETE,
},
tags: tagsConfig,
};
export {
systemConfig,
kmsKeyConfig,
prefixListsConfig,
securityGroupConfig,
fsxnFileSystemConfig,
backupConfig,
fsxnVolumesConfig,
monitoringConfig,
tagsConfig,
};
npx cdk diff
を実行した結果は以下のとおりです。
> npx cdk diff
[Warning at /non-97-dev-stack-fsxn-resources/BackupConstruct/Role] [object Object]
start: Building 388d3d8228d95ba5313dd9409a1349d013788a16bb7c2a9325a4e27a1f4bc897:<AWSアカウントID>-us-east-1
success: Built 388d3d8228d95ba5313dd9409a1349d013788a16bb7c2a9325a4e27a1f4bc897:<AWSアカウントID>-us-east-1
start: Publishing 388d3d8228d95ba5313dd9409a1349d013788a16bb7c2a9325a4e27a1f4bc897:<AWSアカウントID>-us-east-1
success: Published 388d3d8228d95ba5313dd9409a1349d013788a16bb7c2a9325a4e27a1f4bc897:<AWSアカウントID>-us-east-1
Hold on while we create a read-only change set to get a diff with accurate replacement information (use --no-change-set to use a less accurate but faster template-only diff)
Stack non-97-dev-stack-fsxn-resources
Resources
[~] AWS::EC2::PrefixList PlConstruct/PrefixListSmb PlConstructPrefixListSmb3EE1E490
├─ [+] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [+] UpdateReplacePolicy
└─ Retain
[~] AWS::EC2::PrefixList PlConstruct/PrefixListIcmp PlConstructPrefixListIcmp2A394C20
├─ [+] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [+] UpdateReplacePolicy
└─ Retain
[~] AWS::KMS::Key KmsConstruct/Default KmsConstructD4AB01CB
└─ [~] DeletionPolicy
├─ [-] Retain
└─ [+] RetainExceptOnCreate
[~] AWS::KMS::Alias KmsConstruct/Default/Alias KmsConstructAlias090870E2
├─ [+] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [+] UpdateReplacePolicy
└─ Retain
[~] AWS::EC2::SecurityGroup SecurityGroupConstruct/Default SecurityGroupConstructC75D2B69
├─ [+] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [+] UpdateReplacePolicy
└─ Retain
[~] AWS::EC2::SecurityGroupIngress SecurityGroupConstruct/Default/from pl-0d1df59eaa666b077:445 SecurityGroupConstructfrompl0d1df59eaa666b0774452A5CC07E
├─ [+] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [+] UpdateReplacePolicy
└─ Retain
[~] AWS::EC2::SecurityGroupIngress SecurityGroupConstruct/Default/from pl-03be8a39ee35dc634:ICMP Type 8 SecurityGroupConstructfrompl03be8a39ee35dc634ICMPType844A35284
├─ [+] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [+] UpdateReplacePolicy
└─ Retain
[~] AWS::Backup::BackupVault BackupConstruct/Vault BackupConstructVault75ECEF5F
└─ [~] DeletionPolicy
├─ [-] Retain
└─ [+] RetainExceptOnCreate
[~] AWS::Backup::BackupPlan BackupConstruct/BackupPlan BackupConstructBackupPlan467C7241
├─ [+] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [+] UpdateReplacePolicy
└─ Retain
[~] AWS::Backup::BackupSelection BackupConstruct/BackupSelection BackupConstructBackupSelectionC83DBFF7
├─ [+] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [+] UpdateReplacePolicy
└─ Retain
[~] AWS::FSx::Volume FsxnVolumeConstruct/VolTest1 FsxnVolumeConstructVolTest1C3E52B23
├─ [+] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [+] UpdateReplacePolicy
└─ Retain
[~] AWS::FSx::Volume FsxnVolumeConstruct/VolTest2 FsxnVolumeConstructVolTest2D2FEFF56
├─ [+] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [+] UpdateReplacePolicy
└─ Retain
[~] AWS::SNS::Topic MonitoringConstruct/Topic MonitoringConstructTopic9E0A8832
├─ [+] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [+] UpdateReplacePolicy
└─ Retain
[~] AWS::CloudWatch::Alarm MonitoringConstruct/AlarmFsxnFileSystemStorageCapacityUtilization MonitoringConstructAlarmFsxnFileSystemStorageCapacityUtilizationB5337B6D
├─ [+] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [+] UpdateReplacePolicy
└─ Retain
[~] AWS::CloudWatch::Alarm MonitoringConstruct/AlarmFsxnFileSystemNetworkThroughputUtilization MonitoringConstructAlarmFsxnFileSystemNetworkThroughputUtilization7AEBF82B
├─ [+] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [+] UpdateReplacePolicy
└─ Retain
[~] AWS::CloudWatch::Alarm MonitoringConstruct/AlarmFsxnFileSystemFileServerDiskThroughputUtilization MonitoringConstructAlarmFsxnFileSystemFileServerDiskThroughputUtilizationEFE12F39
├─ [+] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [+] UpdateReplacePolicy
└─ Retain
[~] AWS::CloudWatch::Alarm MonitoringConstruct/AlarmFsxnFileSystemDiskIopsUtilization MonitoringConstructAlarmFsxnFileSystemDiskIopsUtilization98F515A9
├─ [+] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [+] UpdateReplacePolicy
└─ Retain
[~] AWS::CloudWatch::Alarm MonitoringConstruct/AlarmFsxnFileSystemCpuutilization MonitoringConstructAlarmFsxnFileSystemCpuutilization08E8374A
├─ [+] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [+] UpdateReplacePolicy
└─ Retain
[~] AWS::CloudWatch::Alarm MonitoringConstruct/AlarmFsvolVolTest1StorageCapacityUtilization MonitoringConstructAlarmFsvolVolTest1StorageCapacityUtilizationB9753F6E
├─ [+] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [+] UpdateReplacePolicy
└─ Retain
[~] AWS::CloudWatch::Alarm MonitoringConstruct/AlarmFsvolVolTest1InodeUtilization MonitoringConstructAlarmFsvolVolTest1InodeUtilization4F19C0BD
├─ [+] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [+] UpdateReplacePolicy
└─ Retain
[~] AWS::CloudWatch::Alarm MonitoringConstruct/AlarmFsvolVolTest2StorageCapacityUtilization MonitoringConstructAlarmFsvolVolTest2StorageCapacityUtilizationBF4D8972
├─ [+] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [+] UpdateReplacePolicy
└─ Retain
[~] AWS::CloudWatch::Alarm MonitoringConstruct/AlarmFsvolVolTest2InodeUtilization MonitoringConstructAlarmFsvolVolTest2InodeUtilizationD3C7593B
├─ [+] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [+] UpdateReplacePolicy
└─ Retain
[~] AWS::CloudWatch::Alarm MonitoringConstruct/AlarmFsvolRootStorageCapacityUtilization MonitoringConstructAlarmFsvolRootStorageCapacityUtilizationF51FEC6F
├─ [+] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [+] UpdateReplacePolicy
└─ Retain
[~] AWS::CloudWatch::Alarm MonitoringConstruct/AlarmFsxnNumberOfBackupJobsFailed MonitoringConstructAlarmFsxnNumberOfBackupJobsFailedFE96A612
├─ [+] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [+] UpdateReplacePolicy
└─ Retain
✨ Number of stacks with differences: 1
ほとんどのリソースでDeletionPolicyはRetainExceptOnCreate
、UpdateReplacePolicyはRetain
が設定されていることが分かります。
AWS::KMS::Key
とAWS::Backup::BackupVault
については、デフォルトでUpdateReplacePolicyはRetain
であるため差分として表示されていません。
ちなみにStack内のリソース数は25個で、更新対象リソース数は24個です。差分の1つはCDKMetadata分です。
RemovalPolicy.RETAIN_ON_UPDATE_OR_DELETE を削除
npx cdk deploy
後、RemovalPolicy.RETAIN_ON_UPDATE_OR_DELETE
の指定をを削除してみます。
npx cdk diff
の結果は以下のとおりです。
> npx cdk diff
[Warning at /non-97-dev-stack-fsxn-resources/BackupConstruct/Role] [object Object]
start: Building d8712f51341a7ac527caa3814722f3f47dea7b4546b88e657a0fe6cd335a5aaf:<AWSアカウントID>-us-east-1
success: Built d8712f51341a7ac527caa3814722f3f47dea7b4546b88e657a0fe6cd335a5aaf:<AWSアカウントID>-us-east-1
start: Publishing d8712f51341a7ac527caa3814722f3f47dea7b4546b88e657a0fe6cd335a5aaf:<AWSアカウントID>-us-east-1
success: Published d8712f51341a7ac527caa3814722f3f47dea7b4546b88e657a0fe6cd335a5aaf:<AWSアカウントID>-us-east-1
Hold on while we create a read-only change set to get a diff with accurate replacement information (use --no-change-set to use a less accurate but faster template-only diff)
Stack non-97-dev-stack-fsxn-resources
Resources
[~] AWS::EC2::PrefixList PlConstruct/PrefixListSmb PlConstructPrefixListSmb3EE1E490
├─ [-] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [-] UpdateReplacePolicy
└─ Retain
[~] AWS::EC2::PrefixList PlConstruct/PrefixListIcmp PlConstructPrefixListIcmp2A394C20
├─ [-] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [-] UpdateReplacePolicy
└─ Retain
[~] AWS::KMS::Key KmsConstruct/Default KmsConstructD4AB01CB
└─ [~] DeletionPolicy
├─ [-] RetainExceptOnCreate
└─ [+] Retain
[~] AWS::KMS::Alias KmsConstruct/Default/Alias KmsConstructAlias090870E2
├─ [-] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [-] UpdateReplacePolicy
└─ Retain
[~] AWS::EC2::SecurityGroup SecurityGroupConstruct/Default SecurityGroupConstructC75D2B69
├─ [-] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [-] UpdateReplacePolicy
└─ Retain
[~] AWS::EC2::SecurityGroupIngress SecurityGroupConstruct/Default/from pl-0d1df59eaa666b077:445 SecurityGroupConstructfrompl0d1df59eaa666b0774452A5CC07E
├─ [-] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [-] UpdateReplacePolicy
└─ Retain
[~] AWS::EC2::SecurityGroupIngress SecurityGroupConstruct/Default/from pl-03be8a39ee35dc634:ICMP Type 8 SecurityGroupConstructfrompl03be8a39ee35dc634ICMPType844A35284
├─ [-] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [-] UpdateReplacePolicy
└─ Retain
[~] AWS::Backup::BackupVault BackupConstruct/Vault BackupConstructVault75ECEF5F
└─ [~] DeletionPolicy
├─ [-] RetainExceptOnCreate
└─ [+] Retain
[~] AWS::Backup::BackupPlan BackupConstruct/BackupPlan BackupConstructBackupPlan467C7241
├─ [-] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [-] UpdateReplacePolicy
└─ Retain
[~] AWS::Backup::BackupSelection BackupConstruct/BackupSelection BackupConstructBackupSelectionC83DBFF7
├─ [-] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [-] UpdateReplacePolicy
└─ Retain
[~] AWS::FSx::Volume FsxnVolumeConstruct/VolTest1 FsxnVolumeConstructVolTest1C3E52B23
├─ [-] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [-] UpdateReplacePolicy
└─ Retain
[~] AWS::FSx::Volume FsxnVolumeConstruct/VolTest2 FsxnVolumeConstructVolTest2D2FEFF56
├─ [-] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [-] UpdateReplacePolicy
└─ Retain
[~] AWS::SNS::Topic MonitoringConstruct/Topic MonitoringConstructTopic9E0A8832
├─ [-] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [-] UpdateReplacePolicy
└─ Retain
[~] AWS::CloudWatch::Alarm MonitoringConstruct/AlarmFsxnFileSystemStorageCapacityUtilization MonitoringConstructAlarmFsxnFileSystemStorageCapacityUtilizationB5337B6D
├─ [-] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [-] UpdateReplacePolicy
└─ Retain
[~] AWS::CloudWatch::Alarm MonitoringConstruct/AlarmFsxnFileSystemNetworkThroughputUtilization MonitoringConstructAlarmFsxnFileSystemNetworkThroughputUtilization7AEBF82B
├─ [-] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [-] UpdateReplacePolicy
└─ Retain
[~] AWS::CloudWatch::Alarm MonitoringConstruct/AlarmFsxnFileSystemFileServerDiskThroughputUtilization MonitoringConstructAlarmFsxnFileSystemFileServerDiskThroughputUtilizationEFE12F39
├─ [-] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [-] UpdateReplacePolicy
└─ Retain
[~] AWS::CloudWatch::Alarm MonitoringConstruct/AlarmFsxnFileSystemDiskIopsUtilization MonitoringConstructAlarmFsxnFileSystemDiskIopsUtilization98F515A9
├─ [-] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [-] UpdateReplacePolicy
└─ Retain
[~] AWS::CloudWatch::Alarm MonitoringConstruct/AlarmFsxnFileSystemCpuutilization MonitoringConstructAlarmFsxnFileSystemCpuutilization08E8374A
├─ [-] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [-] UpdateReplacePolicy
└─ Retain
[~] AWS::CloudWatch::Alarm MonitoringConstruct/AlarmFsvolVolTest1StorageCapacityUtilization MonitoringConstructAlarmFsvolVolTest1StorageCapacityUtilizationB9753F6E
├─ [-] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [-] UpdateReplacePolicy
└─ Retain
[~] AWS::CloudWatch::Alarm MonitoringConstruct/AlarmFsvolVolTest1InodeUtilization MonitoringConstructAlarmFsvolVolTest1InodeUtilization4F19C0BD
├─ [-] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [-] UpdateReplacePolicy
└─ Retain
[~] AWS::CloudWatch::Alarm MonitoringConstruct/AlarmFsvolVolTest2StorageCapacityUtilization MonitoringConstructAlarmFsvolVolTest2StorageCapacityUtilizationBF4D8972
├─ [-] DeletionPolicy
│ └─ RetainExceptOnCreate
└─ [-] UpdateReplacePolicy
└─ Retain
[~] AWS::CloudWatch::Alarm MonitoringConstruct/AlarmFsvolVolTest2InodeUtilization MonitoringConstructAlarmFsvolVolTest2InodeUtilizationD3C7593B
✨ Number of stacks with differences: 1
AWS::KMS::Key
とAWS::Backup::BackupVault
のDeletionPolicyがRetainExceptOnCreate
からRetain
に変更されていることから、デフォルトのDeletionPolicyやUpdateReplacePolicyに戻るようですね。
完全にリソースを削除したい場合や万が一Stackを削除されてしまってもリソースを残したい場合に
AWS CDKを用いて、Stack内の全てのリソースに対してRemovalPolicyを設定してみました。
完全にリソースを削除したい場合や万が一Stackを削除されてしまってもリソースを残したい場合に活用してみてください。
この記事が誰かの助けになれば幸いです。
以上、AWS事業本部 コンサルティング部の のんピ(@non____97)でした!